import React, { useState, useRef } from 'react'
import { Stage, Layer, Line } from 'react-konva'

type Tool = 'pen' | 'eraser'

interface Line {
  tool: Tool
  points: number[]
  color: string
  size: number
}

const DrawingBoard: React.FC = () => {
  const [lines, setLines] = useState<Line[]>([])
  const [tool, setTool] = useState<Tool>('pen')
  const [color, setColor] = useState<string>('#000000')
  const [size, setSize] = useState<number>(5)
  const isDrawing = useRef(false)

  const handleMouseDown = (e: any) => {
    isDrawing.current = true
    const pos = e.target.getStage().getPointerPosition()
    setLines([...lines, { tool, points: [pos.x, pos.y], color, size }])
  }

  const handleMouseMove = (e: any) => {
    if (!isDrawing.current) return

    const stage = e.target.getStage()
    const point = stage.getPointerPosition()
    const lastLine = lines[lines.length - 1]
    lastLine.points = lastLine.points.concat([point.x, point.y])

    lines.splice(lines.length - 1, 1, lastLine)
    setLines([...lines])
  }

  const handleMouseUp = () => {
    isDrawing.current = false
  }

  const handleClear = () => {
    setLines([])
  }

  return (
    <div className="flex flex-col items-center space-y-4 p-4">
      <div className="space-x-2">
        <button
          className={`px-4 py-2 rounded ${tool === 'pen' ? 'bg-blue-500 text-white' : 'bg-gray-200'}`}
          onClick={() => setTool('pen')}
        >
          画笔
        </button>
        <button
          className={`px-4 py-2 rounded ${tool === 'eraser' ? 'bg-blue-500 text-white' : 'bg-gray-200'}`}
          onClick={() => setTool('eraser')}
        >
          橡皮擦
        </button>
        <button className="px-4 py-2 rounded bg-red-500 text-white" onClick={handleClear}>
          清除
        </button>
        <input
          type="color"
          value={color}
          onChange={(e) => setColor(e.target.value)}
          className="w-10 h-10 rounded"
        />
        <input
          type="range"
          min="1"
          max="20"
          value={size}
          onChange={(e) => setSize(Number(e.target.value))}
          className="w-32"
        />
      </div>
      <Stage
        width={800}
        height={600}
        onMouseDown={handleMouseDown}
        onMousemove={handleMouseMove}
        onMouseup={handleMouseUp}
        className="border border-gray-300"
      >
        <Layer>
          {lines.map((line, i) => (
            <Line
              key={i}
              points={line.points}
              stroke={line.tool === 'eraser' ? '#ffffff' : line.color}
              strokeWidth={line.size}
              tension={0.5}
              lineCap="round"
              globalCompositeOperation={
                line.tool === 'eraser' ? 'destination-out' : 'source-over'
              }
            />
          ))}
        </Layer>
      </Stage>
    </div>
  )
}

export default DrawingBoard